package com.oauth.yahoo.server.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.scribe.http.Request;
import org.scribe.http.Response;
import org.scribe.http.Request.Verb;
import org.scribe.oauth.Scribe;
import org.scribe.oauth.Token;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public class YahooUtil {

	private Logger logger= Logger.getLogger("YahooUtil");
	public static JSONObject getData(OAuthConsumer consumer,JSONArray jsonObjSend) throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, ClientProtocolException, IOException, IllegalStateException, JSONException{
		  //Create a HTTP Post request
        
        HttpPost request = new HttpPost("http://mail.yahooapis.com/ws/mail/v1.1/jsonrpc");
        request.addHeader("Content-type", "application/json");
        request.addHeader("Accept", "application/json");
        StringEntity se;
        se = new StringEntity(jsonObjSend.toString());
        request.setEntity(se);
        //Sign the request 
        consumer.sign(request);
        //Constructing an Http Client
        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = httpClient.execute(request);
        // JSON object to hold the information, which is sent to the server
        JSONObject jsonObjRecv = ReadResponse.parseResponse(response);
        return jsonObjRecv;
	}
	
	public static String[] getData(Scribe scribe,JSONArray jsonObjSend1,Token accessToken) throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, ClientProtocolException, IOException, IllegalStateException, JSONException{
		
			//String oldAccessToken = accessToken.getSecret();
        
	       // System.out.println("Oauth token expires in" +provider.getResponseParameters().getAsHeaderElement("oauth_expires_in"));
			SortedMap<String, String> sortedJsonPr = new TreeMap<String,String>();
			//sortedJsonPr.put("AD_request1", "GetUserData,[{}]");
			sortedJsonPr.put("AC_request1", "ListMessages,[{\"fid\":\"Inbox\"," +
					"\"numMid\":\"30\"," +
					"\"numInfo\":\"30\"}]");
			sortedJsonPr.put("AC_request3", "ListFolders,[{}]");	
			System.out.println("Entering");
			String[] resultArr = new String[2];
			int count=0;
	        for (Iterator i = sortedJsonPr.keySet().iterator(); i.hasNext();) {
	        	System.out.println("Entering iteration1");
	            JSONObject jsonObjSend = new JSONObject();

	            String key2 = (String) i.next();
	            String value2 = (String) sortedJsonPr.get(key2);
	            Map<String,String> requestMsgPar = splitter(value2);
	            
	            //Iterates over each API request from the Property file and executes
	            for(Iterator j = requestMsgPar.keySet().iterator(); j.hasNext();){

	                    String key = (String) j.next();
	                    String value = (String) requestMsgPar.get(key);
	                    
	                    JSONArray param = new JSONArray(value);
	                    jsonObjSend.put("params", param);
	                    jsonObjSend.put("method", key);
	                    
	                    //Create a HTTP Post request
	                    Request request = new Request(Verb.POST,"http://mail.yahooapis.com/ws/mail/v1.1/jsonrpc");
	                    //HttpPost request = new HttpPost("http://mail.yahooapis.com/ws/mail/v1.1/jsonrpc");
	                    request.addHeader("Content-type", "application/json");
	                    request.addHeader("Accept", "application/json");
	                    
	                    request.addPayload(jsonObjSend.toString());
//	                    StringEntity se;
//	                    se = new StringEntity(jsonObjSend.toString());
//	                    request.setEntity(se);
	                    //Sign the request
	                    System.out.println("Signing scribe:"+ count);
	                    
	                    scribe.signRequest(request, accessToken);
	                    
	                    Response send = request.send();
	                    
	                    //Constructing an Http Client
//	                    HttpClient httpClient = new DefaultHttpClient();
//	                    HttpResponse response = httpClient.execute(request);
	                    // JSON object to hold the information, which is sent to the server
	                    System.out.println("Trying to get emails");
	                    
	                    
	                    resultArr[count] = send.getBody();
	                    count++;
	                    
	                    
//	                    JSONObject jsonObjRecv = new JSONObject(send.getBody());
//	                    if (jsonObjRecv != null) {
//					         //Printing out the response
//					          System.out.println("JSON output is" +jsonObjRecv.toString(1));
//					         	Logger.getLogger("YahooMail").info("JSON output is" +jsonObjRecv.toString(1));
//					         	//return jsonObjRecv;
//					         }else {
//					        	 System.out.println("JSON op is null");
//					        	 Logger.getLogger("YahooMail").info("JSON output is null");
//					         }
	            		}
	        }
	        
	        return resultArr;
	        
		
//		Request oauthRequest = new Request(Verb.POST,
//				"http://mail.yahooapis.com/ws/mail/v1.1/jsonrpc");
//		oauthRequest.addHeader("Content-type", "application/json");
//		oauthRequest.addHeader("Accept", "application/json");
//
//        oauthRequest.addPayload(jsonObjSend.toString());
//        
////		JSONArray
////		String s = "AD_request1=GetUserData,[{}]  AC_request3=ListFolders,[{}]";
//		
//		scribe.signRequest(oauthRequest, accessToken);
//		Response oauthResponse = oauthRequest.send();
//		String responseBody = oauthResponse.getBody();
//		if(oauthResponse.getCode()!=200){
//			System.out.println(responseBody);
//			throw new RuntimeException("Error while trying to fetch contacts from yahoo. Response Code="+oauthResponse.getCode());
//		}
//		System.out.println("Got Contacts:"+oauthResponse.getCode());
//		System.out.println(responseBody);
		
		
		
//      HttpPost request = new HttpPost("http://mail.yahooapis.com/ws/mail/v1.1/jsonrpc");
//      request.addHeader("Content-type", "application/json");
//      request.addHeader("Accept", "application/json");
//      StringEntity se;
//      se = new StringEntity(jsonObjSend.toString());
//      request.setEntity(se);
//      //Sign the request 
//      //scribe.sign(request);
//      //Constructing an Http Client
//      HttpClient httpClient = new DefaultHttpClient();
//      HttpResponse response = httpClient.execute(request);
      // JSON object to hold the information, which is sent to the server
      //return new JSONObject(responseBody);
	}
	
	public static String getGuid(Scribe scribe, Token accessToken) throws ParserConfigurationException, SAXException, IOException {
		Request oauthGuidRequest = new Request(Verb.GET,
		"http://social.yahooapis.com/v1/me/guid");
		scribe.signRequest(oauthGuidRequest, accessToken);
		Response guidResponse = oauthGuidRequest.send();
		String guidResp = guidResponse.getBody();
		return getGuid(guidResp);
	}
	
	private static String getGuid(String guidResp)
		throws ParserConfigurationException, SAXException, IOException {
	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	DocumentBuilder db = dbf.newDocumentBuilder();
	ByteArrayInputStream bis = new ByteArrayInputStream(guidResp
			.getBytes("UTF-8"));
	Document doc = db.parse(bis);
	doc.getDocumentElement().normalize();
	System.out.println(doc);
	NodeList nodeList = doc.getElementsByTagName("value");
	Node guidItem = nodeList.item(0);
	String guid = guidItem.getTextContent();
	return guid;
	}
	
	public static Map<String,String> splitter(String toBeSplit){
		Map<String,String> map = new LinkedHashMap<String,String>();
		        String[] parts = toBeSplit.split("," , 2);
		        map.put(parts[0], parts[1]);
		        return map;
	}
}
